<?php

App::import('Model', 'User');
App::import('Model', 'Post');
CakePlugin::load('Bitly');
CakePlugin::load('Uploader');
App:: import('Model', 'bitlyAccess');
App::import('Model', 'Account');
App::import('Model', 'tattlrAccount');
App:: import('Controller', 'FutureTweets');
App:: import('Component', 'JqImgcrop');
App::import('View', 'Cropimage');
require '../Vendor/tmhOAuth.php';
require '../Vendor/tmhUtilities.php';

class TweetsController extends AppController {

    //  var $components = array('Auth');
    /*
     * Description of "index"
     * 
     *
     * This function takes the user's search input and the type of search selected ,
     * and redirects him to tweets search results or people search according to the type of search selected
     * @author "Mark Milad"
     */
    public function index() {
        $accountID = $this->Auth->user('accID');
        if($accountID == null){
            $this->Session->setFlash('Please select an account first');
            $this->Redirect('/Tweets');
        }
        if ($this->request->data) {
            $searchKey = $this->request->data['Tweet']['Search'];
            if ($searchKey == '') {
                $this->Session->setFlash('Please specify your search query !');
            } else {

                $type = $this->request->data['Tweet']['TypeOfSearch'];

                if ($type == '0') {
                    $this->redirect(array('action' => 'SearchForTweets', $searchKey, $accountID));
                } else {
                    $this->redirect(array('action' => 'SearchForPeople', $searchKey, $accountID));
                }
            }
        }
    }

    /*
     * Description of "main"
     * @param  "userid","accountid" 
     *
     * This function works on the main textbox and it allows the user to tweet and reply from the same textbox .
     * The function also allows any editor to post a tweet and added it to the future timeline buffer.

     * @author "Sherif Ismail","Menah ElBastawisy"
     */

    public function main() {
        $future = new FutureTweetsController;
        $accountID = $this->Auth->User('accID');
        $userID = $this->Auth->User('userID');
        $this->loadModel('User');
        $this->loadModel('FutureTweet');
        $permission = $this->User->getPermissionLevel($accountID, $userID); //gets the level of permission of the user over this account
        $check = $this->helper($userID, $accountID); //calls the helper method
        if ($this->User->isAdmin($userID)) {
            $permission = 3;
        }
        if ($permission == 0) {
            $this->Session->setFlash('you are not assigned anymore');
        } else {
            if ($check == true) { // if helper didnt face any problem with the checks proceed
                $first = explode(' ', $this->request->data['Tweet']['Text']); //separates the text of the tweeet at every space
                $replycheck = strncmp($first[0], $this->Session->Read('ReplyName2'), max(strlen($first[0]), strlen($this->Session->Read('ReplyName2')))); //checks that the string in the text of the tweet till the first space is the same as the string of the one you want to reply to 
                if ($replycheck == 0 && $this->Session->Read('ReplyName2') != null) {//if the session is not null which means someone clicked on reply and the previous check hold execute the following
                    $this->loadModel('FutureTweet');
                    if ($permission == 1) {//if he is a junior editor
                        $JE = 1;
                        $this->request->data['FutureTweet']['approved'] = false;
                        $this->request->data = $this->FutureTweet->setreplyto($this->request->data, '' . $this->Session->Read('ReplyID'));
                    }
                    if ($permission == 2 or $permission == 3) {//if he is a moderator or editor
                        $this->request->data = $this->FutureTweet->setreplyto($this->request->data, '' . $this->Session->Read('ReplyID'));
                        $this->request->data = $this->FutureTweet->updateapproved($this->request->data); //set approved to 1 because moderators and editors dont need approval from anyone
                    }
                    $message = $future->insertTweet($this->request->data['FutureTweet']);
                    if ($message == 'Tweet has been added successfully') {
                        if ($JE == 1) {
                            $this->Session->setFlash($message . ' and is waiting for approval');
                        } else {
                            $this->Session->setFlash('tweeted');
                        }
                        $_SESSION['ReplyID'] = null; //reset session variable
                        $_SESSION['ReplyName2'] = null; //reset session variable
                        $this->request->data['Tweet']['Text'] = '';
                    } else {
                        $this->Session->setflash($message);
                    }
                } else {
                    /*
                     * Description of "main else part"
                     * @param  "userid","accountid" 
                     *
                     * This part of the function runs when the tweet is not a reply, it adds a tweet in the future tweets table as a junior editor (approved = false)  .
                     *
                     * @author "Ahmed El-Fouly"
                     */
                    if ($permission == 1) {
                        $JE = 1;
                        $this->request->data = $this->FutureTweet->updateapprovedfalse($this->request->data);
                        //Sets approval to false, as this is the JE's tweeting part.
                    } elseif ($permission == 2 or $permission == 3) {//edited by Menah ElBastawisy
                        $this->request->data = $this->FutureTweet->updateapproved($this->request->data); //set approved to 1 since moderators and editors dont need approval from anyone
                    }
                    $message = $future->insertTweet($this->request->data['FutureTweet']);
                    if ($message == 'Tweet has been added successfully') {
                        if ($JE == 1) {
                            $this->Session->setFlash($message . ' and is waiting for approval');
                        } else {
                            $this->Session->setFlash('tweeted');
                        }

                        $this->request->data['Tweet']['Text'] = '';
                    } else {
                        $this->Session->setflash($message);
                    }
                }
            }
        }
    }

    /*
     * Description of "helper"
     * @param  "userid","accountid" 
     *
     * This function checks on the tweet if it is valid and if it is not it sends the suitable failure message to the user  .
     * The function also checks if there is a link in the input text and shorten that that link.
     * @author "Sherif Ismail", "Menah ELBastawisy"
     */

    public function helper($userID, $accountID) {//edited by sherif ismail, Menah ElBastawisy
        if ($this->request->data) {
            $String_TweetText = "" . ($this->request->data['Tweet']['Text']);
            if (strlen($String_TweetText) == 0) {
                $this->Session->setFlash('Write something First');
            } else {
                if (strlen($String_TweetText) < 141) {

                    $x = $this->Tweet->getduplicate($String_TweetText, $accountID);
                    if (count($x) == 0) {
                        $current_time = date('Y-m-d H:i:s');
                        $this->request->data = $this->FutureTweet->update($current_time, $userID, $String_TweetText, $accountID);
                        $this->request->data['Tweet']['Text'] = $String_TweetText;
                        return true;
                    } else {
                        $this->Session->setFlash('A tweet with the specified text already exists and the difference in timing is < 1 day. Twitter will not allow such an action. Kindly enter an alternate date');
                    }
                } else {
                    $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
                    $arraytext = explode(' ', $this->request->data['Tweet']['Text']);
                    foreach ($arraytext as $link) {
                        if (preg_match($reg_exUrl, $link, $url)) {

                            $x = $this->Tweet->getduplicate($String_TweetText, $accountID);
                            if (count($x) == 0) {
                                $current_time = date('Y-m-d H:i:s');
                                $this->request->data = $this->FutureTweet->update($current_time, $userID, $String_TweetText, $accountID);
                                $this->request->data['Tweet']['Text'] = $String_TweetText;
                                return true;
                            } else {
                                $this->Session->setFlash('A tweet with the specified text already exists and the difference in timing is < 1 day. Twitter will not allow such an action. Kindly enter an alternate date');
                            }
                        } else {
                            $this->Session->setFlash('The tweet exceeded the 140 chars');
                        }
                    }
                }
            }
        } else {
            $this->request->data['Tweet']['Text'] = $this->Session->Read('ReplyName'); //sets the content of the textbox to the name you want to reply to (if there is)
            $_SESSION['ReplyName2'] = $this->Session->Read('ReplyName');
            ;
            $_SESSION['ReplyName'] = null;
        }
    }

    /*
     * Description of "reply"
     * @param  "replyid" 
     *
     * This function sets the session variables that will be used to reply.
     * @author "Sherif Ismail"
     */

    public function reply($replyid) {
        $this->loadModel('Account');
        $array = $this->Account->getAccount($replyid);
        $this->Session->write('ReplyName', '@' . $array[0]['Account']['twitterName']);
        $this->Session->write('ReplyID', $replyid);
        $this->redirect(array('action' => 'main'));
    }

    /*
     * Description of "getNumberRetweet"
     * @param  "postID"
     * @return "numRT"   // number of retweet
     * @access public 
     * description of the function:
     * The purpose of this function is to fetch the number of retweets
     * of a certain tweet from the Database to be displayed with the tweet
     * in the tweets view, it takes as a paramter the $postID of the tweet
     * and then it calls in the Tweet Model getNumRetweet($postID) which
     * returns back the number of favourits for this tweet from table Tweets
     * in the database
     * @author "Mo'men el Sawy"
     */

    function getNumberRetweet($postID=NULL) {
        $tempAccount = new Account();
        $check = $tempAccount->accountIsAuthorized($this->Auth->User('accID'));
        if ($check == true) {


            //Fetch tweets
            $status = (array) $tempAccount->connectionRequest($this->Auth->User('accID'))->get('statuses/show/' . $postID);

            if ($status != false) {


                $r = $status['retweet_count'];
                return $r;
            } 
        } else {
            $this->Session->setFlash('You are not authorized to view this data');
        }
    }

    /*
     * Description of "retweetAccounts"
     * @param  "postID"
     * @returns "array"   //array of twitter accounts
     * @acess public    
     * description of the function:
     * this function is made to allow the user to view the twitter
     * accounts that retweeted a certain tweet by passing its ID and then 
     * the function fetch these accounts from the API then passes them to be viewed 
     * @author "Mo'men el Sawy"
     */

    public function retweetAccounts($postID=null) {

        $tempAccount = new Account();

        $check = $tempAccount->accountIsAuthorized($this->Auth->User('accID'));
        if ($check == true) {

            $array = array();
            $users = (array) $tempAccount->connectionRequest($this->Auth->User('accID'))->get('statuses/' . $postID . '/retweeted_by');
            if ($users != false) {

                $i = 0;
                $j = 0;
                foreach ($users as $json) {
                    $user = (array) $json;
                    //    $mysql_format = date("Y-m-d H:i:s", strtotime($post[$j]['created_at']));


                    $array[$i]['name'] = $user['name'];
                    $array[$i]['profile_image_url_https'] = $user['profile_image_url_https'];
                    $array[$i]['followers_count'] = $user['followers_count'];
                    $array[$i]['friends_count'] = $user['friends_count'];
                    $array[$i]['statuses_count'] = $user['statuses_count'];
                    $array[$i]['screen_name'] = $user['screen_name'];
                    $array[$i]['followers_count'] = $user['followers_count'];
                    $array[$i]['description'] = $user['description'];

                    $i++;
                }

                $this->set('array', $array);
                return $array;
            } else {
                $this->Session->SetFlash('Connection Error!');
            }
        } else {
            $this->Session->SetFlash('You are not authorized to view this data');
        }
    }

    /*
     * Description of "SearchForTweets"
     * @param  String $searchKey 
     * @param  String $accountID 
     *
     * This function searches for tweets containing $searchKey via twitter API
     * @author "Mark Milad"
     */

    public function SearchForTweets($searchKey, $accountID) {
        $accountID = $this->Auth->user('accID');
        if($accountID == null){
            $this->Session->setFlash('Please select an account first');
            $this->Redirect('/Tweets');
        }
        if ($this->request->data) {
            $searchKey = $this->request->data['Tweet']['Search'];
            if ($searchKey == '') {
                $this->Session->setFlash('Please specify your search query !');
            } else {

                $type = $this->request->data['Tweet']['TypeOfSearch'];

                if ($type == '0') {
                    $this->redirect(array('action' => 'SearchForTweets', $searchKey, $accountID));
                } else {
                    $this->redirect(array('action' => 'SearchForPeople', $searchKey, $accountID));
                }
            }
        }

        $tempAccount = new Account();
        $array = array();
        $status = (array) $tempAccount->connectionRequest($accountID)->get('search', array('q' => $searchKey));
        $i = 0;

        foreach ($status['results'] as $json) {
            $post = (array) $json;
            $mysql_format = date("Y-m-d H:i:s", strtotime($post['created_at']));

            $array[$i]['key'] = $searchKey;
            $array[$i]['accountID'] = $accountID;
            $array[$i]['username'] = $post['from_user_name'];
            $array[$i]['ProfilePic'] = $post['profile_image_url'];
            $array[$i]['name'] = $post['from_user'];
            $array[$i]['tweetID'] = $post['id_str'];
            $array[$i]['text'] = $post['text'];

            $array[$i++]['time'] = $mysql_format;
        }

        $this->set('tweets', $array);
    }

    /*
     * Description of "SearchForPeople"
     * @param  String $searchKey 
     * @param  String $accountID 
     * 
     * This function searches for People whose names contain $searchKey via twitter API
     * @author "Mark Milad"
     */

    public function SearchForPeople($searchKey, $accountID) {
        $accountID = $this->Auth->user('accID');
        if($accountID == null){
            $this->Session->setFlash('Please select an account first');
            $this->Redirect('/Tweets');
        }
        if ($this->request->data) {
            $searchKey = $this->request->data['Tweet']['Search'];
            if ($searchKey == '') {
                $this->Session->setFlash('Please specify your search query !');
            } else {

                $type = $this->request->data['Tweet']['TypeOfSearch'];

                if ($type == '0') {
                    $this->redirect(array('action' => 'SearchForTweets', $searchKey, $accountID));
                } else {
                    $this->redirect(array('action' => 'SearchForPeople', $searchKey, $accountID));
                }
            }
        }

        $tempAccount = new Account();
        $array = array();
        $status = (array) $tempAccount->connectionRequest($accountID)->get('users/search', array('q' => $searchKey));
        $i = 0;

        foreach ($status as $json) {
            $post = (array) $json;
            $array[$i]['key'] = $searchKey;
            $array[$i]['accountID'] = $accountID;
            $array[$i]['ScreenName'] = $post['screen_name'];
            $array[$i]['name'] = $post['name'];
            $array[$i]['ProfilePic'] = $post['profile_image_url'];
            $array[$i]['NumOfTweets'] = $post['statuses_count'];
            $array[$i]['NumOfFollowers'] = $post['followers_count'];
            $array[$i]['following'] = $post['following'];

            if ($post['description'] == '') {
                $array[$i++]['description'] = "-- This user hasn't written any description yet --";
            } else {
                $array[$i++]['description'] = $post['description'];
            }
        }

        $this->set('users', $array);
    }

    /**
     * Posts a tweet with an uploaded image
     *
     * @access: public
     *
     * @author "Menah ElBastawisy"
     */
    public function upload() {
        $result = ClassRegistry::init('tattlrAccount')->find('all', array('conditions' => array('accID' => $this->Auth->User('accID')), 'fields' => array('oauthToken', 'oauth_token_secret')));
        $tmhOAuth = new tmhOAuth(array(
                    'consumer_key' => 'S9Ww3avoaAONgzqU27DKMQ',
                    'consumer_secret' => 'gPcguIyyKbZlCrlBsKDIKqNCDqu558tfkRdsipoGw',
                    'user_token' => $result['0']['tattlrAccount']['oauthToken'],
                    'user_secret' => $result['0']['tattlrAccount']['oauth_token_secret'],
                ));
        $uploadImage = new JqImgcropComponent();
        if (!empty($this->request->data)) {
            $String_TweetText = "" . ($this->request->data['Tweet']['text']);
            if ((strlen($String_TweetText) == 0) || ($this->request->data['Tweet']['image'] == NULL)) {
                $this->Session->setFlash('Please choose a file and type something first.');
                return;
            }
            $uploaded = $uploadImage->uploadImage($this->request->data['Tweet']['image'], 'img/', '');
            $this->set('uploaded', $uploaded);
            $image = "C:\wamp\www\cakephp\app\webroot\img/" . $uploaded['imageName'];
            $code = $tmhOAuth->request(
                    'POST', 'http://upload.twitter.com/1/statuses/update_with_media.json', array(
                'status' => $this->request->data['Tweet']['text'],
                'media[]' => "@{$image};type=image/jpeg;filename={$image}"
                    ), true, // use auth
                    true  // multipart
            );
            if ($code == 200) {
                $this->Session->setFlash('Your tweet was posted successfully!');
                $this->request->data = '';
            } else {
                $this->Session->setFlash('Something went wrong, your tweet was not posted!');
            }
        }
    }

    /*
     * Description of "view"
     * @param  String $userName	 
     * @param  String $tweetText	 
     * @param  TIMEDATE $time	 
     * @param  String $searchKey	 
     * @param  String $accountID	 
     *
     * This function sends the selected tweet's data to the view 
     * @author "Mark Milad"
     */

    public function view($userName, $tweetText, $time, $searchKey, $accountID) {
        $this->set('tweet', array('name' => $userName, 'text' => $tweetText, 'time' => $time, 'key' => $searchKey, 'accountID' => $accountID));
    }

    /*
     * Description of "userview"
     * @param  String $ScreenName	 
     * @param  String $fullName	 
     * @param  String $description	 
     * @param  String $searchKey	 
     * @param  String $accountID	 
     *
     * This function sends the selected users's data to the view 
     * @author "Mark Milad"
     */

    public function userview($ScreenName, $fullName, $description, $searchKey, $accountID) {
        $this->set('user', array('username' => $ScreenName, 'name' => $fullName, 'description' => $description, 'key' => $searchKey, 'accountID' => $accountID));
    }

    /*
     * Description of "userview1"
     * @param  String $ScreenName	 
     * @param  String $fullName	 
     * @param  String $searchKey	 
     * @param  String $accountID
     * 	 
     * when the user selects the username of a user in a tweet search , this function sends the selected user's data to the view 
     * @author "Mark Milad"
     */

    public function userview1($ScreenName, $fullName, $searchKey, $accountID) {
        $this->set('user', array('username' => $ScreenName, 'name' => $fullName, 'key' => $searchKey, 'accountID' => $accountID));
    }

    /**
     * Description of function "deleteTweets"
     * @param string $postID
     * @return void 
     * 
     * Description :
     * A function taking the post ID as an input and checks if current user have
     * enough permissions and then handles the deleting in the model tweet to 
     * a function named deleteTweets
     * 
     * @author "Omar Elshal"
     */
    function deleteTweets($postID) {

        $userID1 = $this->Auth->User('userID');
        $accID1 = $this->Auth->User('accID');

        $permissionLevel = ClassRegistry::init('User')->getPermissionLevel($accID1, $userID1);

        if ($permissionLevel == 5) {
            $currUser = $userID1;

            if ($this->Tweet->deleteT($postID, $currUser)) {
                $this->Session->setFlash('Tweet deleted successfully !');
                $this->redirect('/Users/viewUsers');
            } else {
                $this->Session->setFlash('Tweet does not exist');
            }
        } else {
            $this->Session->setFlash("You are not authorized to do such Action! ");
            $this->redirect('/Users/viewUsers');
        }
    }

    /**
     * Unfavorites a tweet
     *
     * @access: public
     * @param: $tweetID, the id of the tweet to unfavorite
     *
     * @author "Hussein Abo El Seoud"
     */
    public function unfavorite($tweetID, $home) {
        $tempAccount = new Account();
        $deleted = (array) $tempAccount->connectionRequest($this->Auth->User('accID'))->get('statuses/show/' . $tweetID);
        if ($deleted['error']) {
            $this->Session->setFlash("Sorry the tweet was deleted, please refresh the page.");
        } else {
            $this->Tweet->unfavorite($this->Auth->User('accID'), $tweetID);
            $post = new Post();
            if ($home == 0) {
                return $this->redirect(array('controller' => 'Posts', 'action' => 'index'));
            } else {
                return $this->redirect(array('controller' => 'Posts', 'action' => 'fetchHome'));
            }
        }
    }

    /*
     * Description of "favorite"
     * @params "postid" , "home"
     *
     * This function Passes the right parameters to the favourite function in the model and sets the appropriate message if something goes wrong.
     * @author "Sherif Ismail"
     */

    Public function favorite($postid, $home) {
        $result = $this->Tweet->favorite($this->Auth->user('accID'), $postid, $home);
        if ($result == false) {
            $this->Session->SetFlash('Something went wrong.Please Refresh the page and try again');
        }
        if ($home == '0') {
            $this->redirect(array('controller' => 'Posts', 'action' => 'index'));
        } else {
            $this->redirect(array('controller' => 'Posts', 'action' => 'fetchHome'));
        }
    }

    /**
     * Retweets a tweet
     *
     * @access: public
     * @param: $tweetID, the id of the tweet to be retweeted
     *
     * @author "Menah ELBastawisy"
     */
    public function retweet($tweetID, $home) {

        $check = $this->Tweet->retweetTweet($this->Auth->User('accID'), $tweetID, $home);
        if ($check == TRUE) {
            $this->Session->SetFlash('The tweet was retweeted successfully');
            if ($home == 0) {
                $this->redirect('/posts');
            } else {
                $this->redirect('/posts/fetchHome');
            }
        } else {
            $this->Session->SetFlash('This tweet no longer exists please refresh the page!');
            if ($home == 0) {

                $this->redirect('/posts');
            } else {
                $this->redirect('/posts/fetchHome');
            }
        }
    }

    /*
     * @access: public
     * @param: $postID, $home
     * Description: This function checks whether if the
     * user who requested to retweet is a Junior editor or is an Editor/Moderator
     * and calls the suitable function accordingly, and passes along the variable
     * $home for future usage in the functions called.
     * @author: Ahmed El-Fouly
     */

    public function retweetPermission($postID, $home) {
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $this->loadModel('User');
        $permission = $this->User->getPermissionLevel($accID, $userID);
        if ($permission == 1) { //Check if he is a JE then call the function in the FutureTweetsController
            $this->redirect(array('controller' => 'FutureTweets', 'action' => 'retweet', $postID, $home, $userID, $accID));
        } else {
            $this->retweet($postID, $home);
        }
    }

    /**
     * undo retweets 
     *
     * @access: public
     * @param: $tweetID, the id of the tweet to be unretweeted
     *
     * @author "Menah ELBastawisy"
     */
    public function undoRetweet($tweetID) {
        $check = $this->Tweet->unRetweet($this->Auth->User('accID'), $tweetID);
        if ($check == TRUE) {
            $this->redirect('/posts');
        } else {
            $this->Session->SetFlash('This tweet no longer exists please refresh the page!');
            $this->redirect('/posts');
        }
    }

    /**
     * Description of post_to_twitter
     *
     * @param $arraydata , the tweet that should be posted
     *
     * calling the function post_to_twitter from the model
     *
     * @author Youssef Madkour
     */
    public function post_to_twitter($arraydata) {

        $this->Tweet->post_to_twitter($arraydata);
    }

    /**
     * Description of deletetweetCron
     *
     * @param $tweetID , tweet id in twitter
     * @param $accId, account id in twitter
     *
     * delete the tweet from twitter and from the database from tables (tweet,post)
     *
     * @author Youssef Madkour
     */
    public function deletetweetCron($tweetID, $accID) {
        $post = new Post();
        $tempAccount = new Account();
        $tempAccount->connectionRequest($accID)->post('statuses/destroy/' . $tweetID);
        $this->Tweet->delete($tweetID);
        $post->delete($tweetID);
    }
	  /**
     * uploads an image to the server
     *
     * @access: public
     * 
     *
     * @author "Menah ELBastawisy"
     */
    public function upload_image() {

        if (!empty($this->request->data)) {
            if ($this->request->data['Tweet']['image']['name'] == NULL) {
                $this->Session->setFlash('Please a choose a photo first!');
                return;
            }
            $uploadImage = new JqImgcropComponent();
            $uploaded = $uploadImage->uploadImage($this->request->data['Tweet']['image'], 'img', '');
            $this->set('uploaded', $uploaded);
            $this->Session->setFlash('please type in your tweet and choose the same photo again in the textbox');
        }
    }

    /**
     * posts a tweet containing a photo to twitter
     *
     * @access: public
     * @param: $tweet, array of a future tweet 
     * @return: boolean value
     *
     * @author "Menah ELBastawisy"
     */
    function post_image_tweet($tweet) {
        $result = ClassRegistry::init('tattlrAccount')->find('all', array('conditions' => array('accID' => $tweet['accID']), 'fields' => array('oauthToken', 'oauth_token_secret')));
        $tmhOAuth = new tmhOAuth(array(
                    'consumer_key' => 'S9Ww3avoaAONgzqU27DKMQ',
                    'consumer_secret' => 'gPcguIyyKbZlCrlBsKDIKqNCDqu558tfkRdsipoGw',
                    'user_token' => $result['0']['tattlrAccount']['oauthToken'],
                    'user_secret' => $result['0']['tattlrAccount']['oauth_token_secret'],
                ));
        $array = explode('fakepath', $tweet['imageName']);
        $trim = trim($array['1'], "\'");
        $image = "C:\wamp\www\cakephp\app\webroot\img/" . $trim;
        $code = $tmhOAuth->request(
                'POST', 'http://upload.twitter.com/1/statuses/update_with_media.json', array(
            'status' => $tweet['tweetText'],
            'media[]' => "@{$image};type=image/jpeg;filename={$image}"
                ), true, // use auth
                true  // multipart
        );

        if ($code == 200) {

            return TRUE;
        } else {
            return FALSE;
        }
    }

}